//
//  LoginCodeVerifyVC.swift
//  LeGou
//
//  Created by lxm on 2022/7/26.
//

import UIKit

class LoginCodeVerifyVC: ZMViewController, XMCodeInputViewDelegate {

    //MARK:--------------------属性--------------------
    @IBOutlet weak var codeView: XMCodeInputView!

    var phone : String = ""
    
    var openId : String?
    
    var nickname = ""
    
    //MARK:--------------------UI控件--------------------
    @IBOutlet weak var loginBtn: UIButton!
    
    @IBOutlet weak var phoneLabel: UILabel!
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
    }
    
    //MARK:--------------------UI--------------------
    func setUI() {
        title = ""
        codeView.inputCount = 6
        codeView.space = 8
        let con = XMCodeInputCellConfig()
        con.hideLine = true
        con.borderColor = "#EAEAEA".zm.hex()
        con.borderWidth = 1
        con.securityInput = true
        con.cornerRadius = 8
        con.backGourndColor = .white
        codeView.cellConfig = con
        codeView.delegate = self
        codeView.reaload()
        codeView.collectionView.backgroundColor = "#F5F5F5".zm.hex()
        codeView.becomeFirstResponder()
        phoneLabel.text = "已发送验证码至\(phone.zm.hidPhone())"
    }
    
    func addConstraints() {
        
    }
    
    //MARK:--------------------methods--------------------
    func bindAction() {
        codeView.textField.rx.text.orEmpty.map({$0.count == 6}).subscribe(onNext:{ [unowned self] resp in
            self.loginBtn.isEnabled = resp
            self.loginBtn.backgroundColor = resp ? Style.mainColor : Style.disableColor
        }).disposed(by: disposeBag)
    }
    
    // 重写返回按钮
    override func customBackButton() -> UIButton? {
        let btn = ZMUtil.button(title: "返回", image: UIImage.init(named: "back_18"), font: UIFont.systemFont(ofSize: 18), color: .black)
        btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -16, bottom: 0, right: 0)
        btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
        return btn
    }
    
    @IBAction func onLogin(_ sender: Any) {
        var request : ZMApiProvider!
        if let openId = openId {
            // 第三方登录绑定手机
            request = LoginAPI.wxRegister(["phone" : phone, "wxOpenId" : openId, "captcha" : codeView.text, "wxName" : nickname])
        } else {
            request = LoginAPI.loginOrRegister(["captcha" : codeView.text, "phone" : phone])
        }
        ZMToast.showActivity()
        request.rxRequest(type: LoginModels.LoginResponse.self).flatMap { resp -> Observable<CommonModels.UserInfo> in
            // 登录成功
            ZMAppShareData.share.loginInfo = resp
            // 拉取用户信息
            return MineAPI.userInfo([:]).rxRequest(type: CommonModels.UserInfo.self)
        }.subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            ZMAppShareData.share.userInfo.accept(resp)
            ZMAppShareData.share.saveUserInfo()
            self.lgoinSuccessGoNext()
        }, onError: { _ in
            self.codeView.textField.text = ""
            self.codeView.textField.sendActions(for: .editingChanged)
            self.codeView.clear()
        }).disposed(by: disposeBag)
    }
    
    
    /// 登录成功后去往的页面
    func lgoinSuccessGoNext() {
        if let vc = LoginService.shared.checkIsInfoOkAndNextVC() {
            replace(vc)
        } else {
            // 没问题可以进入app了
            ZMJumpHelper.destroy(FromVC: self, toFirstClass: LoginVC.classForCoder(), isContainSelf: true, isContainFirst: true)
            navigationController?.popViewController(animated: true)
        }
    }
    

    //MARK:--------------------delegate--------------------
    func inputComplete(_ text: String) {
        print(text)
    }
}
